"""
Verifies configuration modules

>>> from mod454 import testconf
>>> check_dataconf( testconf )

"""
import atlas
import sys, inspect

ERR_FLAG = False

def error(msg):
    "Error message reporting"
    global ERR_FLAG
    atlas.error( msg )
    ERR_FLAG = True

def check_attr( conf, name ):
    """
    Checks for the presence of an attribute
    """
    if not hasattr(conf, name):
        error( "attribute '%s' must be defined in the config module" % name )

def check_function( conf, name ):
    """
    Checks for the presence of a function
    """
    if hasattr(conf, name):
        func = getattr(conf, name)
        if not inspect.isfunction( func ):
            error( "config module attribute:'%s' must be a function" % name )
    else:
        error( "function '%s' must be defined in the config module" % name )

def check_class( conf, name ):
    """
    Checks for the presence of a function
    """
    if hasattr(conf, name):
        klass = getattr(conf, name)
        if not inspect.isclass( klass ):
            error( "config module attribute:'%s' must be a class" % name )
    else:
        error( "class '%s' must be defined in the configuration module" % name )

def check_dataconf( conf ):
    """
    Checks a data configuration file
    """
    global ERR_FLAG
    ERR_FLAG = False
    
    attrs = [   
        "SQL_URI", "HDF_DATABASE", 
        "LOADER_ENABLED", "EXPORTER_ENABLED",
        "FITTER_ENABLED", "PREDICTOR_ENABLED", 
        "SIGMA", "WIDTH", "DATA_LABEL",
        "FIT_LABEL", "PEAK_LABEL", "EXCLUSION_ZONE", 
        "LEFT_SHIFT", "RIGHT_SHIFT", "MINIMUM_PEAK_SIZE", "CLOBBER", 
        "EXPORT_DIR", "EXPORT_LABELS", "DATA_SIZE"
        ]

    for attr in attrs:
        check_attr( conf, attr)
    
    funcs = [ "LOADER", "FITTER", "PREDICTOR", "EXPORTER" ]
    for func in funcs:
        check_function( conf, func)

    if ERR_FLAG:
        sys.exit()

def check_webconf( conf ):
    """
    Checks a web configuration file
    """
    global ERR_FLAG
    ERR_FLAG = False
    
    attrs = [ "SQL_URI", "HDF_DATABASE", 
        "PLOT_CHOICES", "PLOT_MAPPER", "ZOOM_LEVELS", "LEVELS", "CHROM_FIELDS",
        "SOCKET_PORT", "SOCKET_HOST", "THREAD_POOL" ]
    
    for attr in attrs:
        check_attr( conf, attr)

    if ERR_FLAG:
        sys.exit()

def test(verbose=0):
    """
    Main testrunnner
    """
    import doctest
    doctest.testmod( optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE, verbose=verbose )

if __name__ == '__main__':
    test(verbose=0)
